<!--组织机构管理的添加和编辑成员-->
<template>
  <div class="app-container" >
    <el-form
      class="add-panel1"
      label-position="right"
      :model="tenat"
      :rules = "rules"
      label-width="130px"
      ref="tenat"
    >
      <el-form-item>
        <div class="panel" style="margin-left:30%">
            <el-row>
              <el-avatar :src="tenat.salt" shape="square" :size="100" style="margin-left:10px"/>
            </el-row>
            <!-- 文件上传按钮 -->
            <el-row>
              <el-button style="margin:10px 0" type="success" icon="el-icon-upload" @click="imagecropperShow=true">
                 {{tenat.salt == null ? '上传' : '更新'}}头像
              </el-button>
            </el-row>
        </div>
      </el-form-item>
      <el-form-item prop="nickName" label="成员名称:">
        <el-input type="text" prefix-icon="el-icon-edit-outline" placeholder="请输入成员名称"
                  clearable v-model="tenat.nickName" />
      </el-form-item>

      <el-form-item prop="username" label="成员账号:">
        <el-input type="text" prefix-icon="el-icon-edit-outline" placeholder="请输入成员账号"
                  v-model="tenat.username" :disabled="!flag" onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"/>
      </el-form-item>

      <el-form-item hidden="true" prop="category">
        <el-input v-model="tenat.category" hidden="true"></el-input>
      </el-form-item>

      <el-form-item prop="email" label="邮箱地址:">
        <el-input type="email" prefix-icon="el-icon-edit-outline"
          v-model="tenat.email" placeholder="请输入邮箱地址"></el-input>
      </el-form-item>

      <el-form-item prop="companyId" label="所属劳务公司">
        <el-select v-model="tenat.companyId" placeholder="请选择劳务公司" style="width:100%" @change="getRoleList">
          <el-option
            v-for="item in corpLists"
            :key="item.corpName"
            :label="item.corpName"
            :value="item.companyId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="roleName" label="所属角色:">
        <el-select v-model="tenat.roleName" style="width:100%" placeholder="请选择所属角色">
          <el-option
            v-for="item in roleLists"
            :key="item.id"
            :label="item.roleName"
            :value="item.roleName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="password" label="登录密码:"  v-if="flag">
        <el-input type="password" placeholder="登录密码" prefix-icon="el-icon-edit-outline"
                  v-model="tenat.password"/>
      </el-form-item>
      <el-form-item prop="rePassword" label="确认密码:" v-if="flag">
        <el-input type="password" placeholder="确认密码" prefix-icon="el-icon-edit-outline"
                  v-model="tenat.rePassword"/>
      </el-form-item>
      <el-form-item label="备注信息:" >
        <el-input type="textarea" placeholder="请输入内容" prefix-icon="el-icon-edit-outline"
                  v-model="tenat.description"/>
      </el-form-item>
      <el-form-item class="add-btn">
        <el-button type="primary" @click="check">提交</el-button>
      </el-form-item>
    </el-form>
    <image-cropper
      v-show="imagecropperShow"
      :width="300"
      :height="300"
      :key="imagecropperKey"
      :url="BASE_API+'/sys/file/uploadImg'"
      field="file"
      @close="close"
      @crop-upload-success="cropSuccess"/>
  </div>
</template>
<script>
import tenatApi from '@/api/tenant'
import ImageCropper from '@/components/ImageCropper'
import corpApi from '@/api/corp.js'
import roleApi from '@/api/acl/role.js'

const tenantForm={
  nickName:'',
  username:'',
  email:'',
  salt:'',
  companyId:'',
  roleName:'所属角色1',
  roleId:'',
  password:'',
  rePassword:'',
  description:'',
  category:'2'
}
export default {
  components: { ImageCropper },
  data() {
    var validUsername = (rule, value, callback) => {
      if(value != '' && value != null&& this.flag) {
        tenatApi.usernameIsExist(value).then(res => {
          if(res.data.exist) {
            callback(new Error('该用户名已存在，请重新输入'));
          } else {
            if(value.length <3 || value.length > 15) {
              callback(new Error('账号不能小于3位且不能大于15位'));
            }
            callback()
          }
        })
      }else{
        callback()
      }
    }
    var validatePass = (rule, value, callback) => {
      if(this.flag){
        if (value === '' || value == null) {
          callback(new Error('请输入登录密码'));
        } else {
          if(value.length <6 || value.length > 20) {
            callback(new Error('密码不能小于6位且不能大于20位'));
          }
          if (this.tenat.rePassword !== '') {
            this.$refs.tenat.validateField('rePassword');
          }
          callback();
        }
      }else{
        callback()
      }
      
    }
    var validatePass2 = (rule, value, callback) => {
      if(this.flag){
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.tenat.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      }else{
        callback()
      }
    }
    var checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (value != '' && value !=null) {
        if (mailReg.test(value)) {
            callback()
        } else {
            callback(new Error('请输入正确的邮箱格式'))
        }
      } else {
        callback()
      }
    }
    return {
      roleLists:[{
        id:'',
        roleName:''
      }],
      corpLists:[{corpName: '项目方(默认)',
                  companyId: '0'}],
      flag: true,
      //上传弹框组件是否显示
      imagecropperShow:false,
      imagecropperKey:0,//上传组件key值
      BASE_API:process.env.BASE_API, //获取dev.env.js里面地址
      category:3,
      tenat:tenantForm,
      rules: {
        nickName:[
          { required: true, message: '请输入成员名称', trigger: 'blur' }
        ],
        username:[
          { required: true, message: '请输入成员账号', trigger: 'blur' },
          { validator: validUsername, trigger: 'blur'}
        ],
        // email:[
        //   { required: false, message: '请输入邮箱地址', trigger: 'change' },
        //   { validator: checkEmail, trigger: 'blur' }
        // ],
        companyId:[
          { required: true, message: '请选择所属劳务公司', trigger: 'blur' }
        ],
        roleName:[
          { required: true, message: '请选择所属角色', trigger: 'blur' }
        ],
        password:[
          { validator: validatePass, trigger: 'blur' },
          { required: true, message: '请输入登录密码', trigger: 'blur' }
        ],
        rePassword:[
          { validator: validatePass2, trigger: 'blur' },
          { required: true, message: '请再次输入密码', trigger: 'blur' }
        ],
        // affiliatedCompany:[
        //   { required: true, message: '请输入所属企业', trigger: 'change' }
        // ]
      }
    }
  },
  created() {//页面渲染之前执行
    //获取路由id值
    // this.getRoleList('0')

    if(this.$route.params && this.$route.params.id) {
      // console.log('czc');
      const id = this.$route.params.id
      this.getTenant(id)
      this.getRoleList(this.tenat.companyId)
      this.flag = false

    } else {
      //表单数据清空
      this.tenat = {}
      this.tenat.companyId = '0'
      this.roleLists = this.getRoleList('0')
    }
    //获取下拉框的角色列表
    this.getCorpList()


  },
  methods: {
    getRoleList(companyId) {
      if(this.tenat.roleName != null) {
        this.tenat.roleName = ''
      }

      roleApi.getRoleListByCompanyId(companyId).then(res => {
        this.roleLists = res.data.roles
      })
    },
    close() { //关闭上传弹框的方法
        this.imagecropperShow=false
        //上传组件初始化
        this.imagecropperKey = this.imagecropperKey+1
    },
    //上传成功方法
    cropSuccess(data) {
        this.imagecropperShow=false
        //上传之后接口返回图片地址
        // this.avatar = data.imgurl
        this.tenat.salt = data.imgurl
        // this.user.salt = this.avatar
        this.imagecropperKey = this.imagecropperKey+1
        // accountApi.saveUser(this.user).then(response => {
        //     this.loading = false
        //     if (response.success) {
        //         this.$message({
        //             type: 'success',
        //             message: response.message
        //         })
        //     }
        //     this.tenat.avatar = data.imgUrl
        //     // this.$store.commit('SET_AVATAR',data.imgurl)
        // }).catch(() => {
        //     this.loading = false
        // })
    },
    getTenantRoleList() {
      tenatApi.getTenantRoleList(this.category).then(res=>{
        this.roleLists=res.data.roleLists
      })
    },
    check() {
      this.$refs.tenat.validate(valid => {
        // 如果验证失败，不发送请求

        if (!valid) {
          return false
        }
        this.saveOrUpdate()
      })
    },
    //根据id查询
    getTenant(id) {
      // console.log("============");
      tenatApi.getTenantById(id)
        .then(response => {
          this.tenat = response.data.userinfo
          console.log(this.tenat)
        })
    },
    getCorpList() {
      corpApi.listByProjectId().then(res => {
        let date = res.data.data.records
        let data = this.corpLists
        date.forEach(function(item,index) {
            data.push({corpName: item.name,companyId: item.serviceCorporationId+''})
        })
        this.corpLists = data
      })
    },
    //添加
    save() {
      this.tenat.category=2
      let roleName = this.tenat.roleName
      let roleId = ''
      this.roleLists.forEach(function(item,index) {
        if(roleName == item.roleName) {
          roleId = item.id
        }
      })
      this.tenat.roleId = roleId
      tenatApi.saveTenat(this.tenat)
        .then(response => {
          //提示
          if(response.success){
            this.$message({
              type: 'success',
              message: '添加成功!'
            })
            //跳转列表页面，使用路由跳转方式实现
            this.$router.push({path:'/system/organization'})
          }
        }).catch(err=>{
            this.$message.error('添加失败,请检查输入信息')
        })
    },
    //修改
    update() {
      this.tenat.category=2
      let roleName = this.tenat.roleName
      let roleId = ''
      this.roleLists.forEach(function(item,index) {
        if(roleName == item.roleName) {
          roleId = item.id
        }
      })
      if(roleId!= ''){
        this.tenat.roleId = roleId
      }
      tenatApi.updateTenant(this.tenat)
        .then(response => {
          //提示
          if(response.success){
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            //跳转列表页面，使用路由跳转方式实现
            this.$router.push({path:'/system/organization'})
          }
        }).catch(err=>{
            this.$message.error('修改失败,请检查输入信息')
        })
    },
    saveOrUpdate() {
      //判断添加还是修改
      if(!this.tenat.id) { //没有id，做添加
        this.save();
      }else {//修改
        this.update()
      }
    }
  }
}
</script>

<style scoped>
.add-btn{
  text-align: center;
}
.add-panel1{
  background-color: white;
  padding: 20px 25% 20px 25%;
}
</style>
